package timeTaskList

import (
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/container/glist"
	"github.com/gogf/gf/container/gtype"
	"github.com/gogf/gf/os/gfile"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/os/gtimer"
	"github.com/gogf/gf/util/gconv"
	"time"
)

var L *glist.List

type SendMap struct {
	//{"fromUserId":"客服发问！！！","toUserId":"aaaaa","content":"skjhgdajgdaj","chatType":"group"}
	FromUserID *gtype.String
	ToUserID   *gtype.String
	Content    *gtype.String
	ChatType   *gtype.String
	TimeStamp  *gtype.Int
}

//初始化，从文件中获取中断时间的任务，中断期间会以json格式保存任务
func Start() {
	var a = make([]SendMap, 0)
	sm := gfile.GetBytes("logs/send_map.txt")
	if string(sm) != "" {
		err := json.Unmarshal(sm, &a)
		if err != nil {
			glog.Error(err)
			return
		}
		//放入list
		for _, v := range a {
			L.PushFront(SendMap{
				FromUserID: v.FromUserID,
				ToUserID:   v.ToUserID,
				Content:    v.Content,
				ChatType:   v.ChatType,
				TimeStamp:  v.TimeStamp,
			})
		}
	}
}

//
func Delete(toUserID string)  {
	//gl := glist.Element{}
	//L.Iterator(func(e *glist.Element) bool {
	//	value := e.Value.(SendMap)
	//	if value.TimeStamp.Val() < gconv.Int(time.Now().Unix()) {
	//		fmt.Println(value.ToUserID)
	//		//发送系统消息
	//		gl = e.Value
	//		return false
	//	}
	//	return true
	//})
	//L.Removes()
}

//中断时将数据写入send_map.txt
func Interrupt() {
	text, err := L.MarshalJSON()
	if err != nil {
		glog.Error(err)
		return
	}
	err = gfile.PutContents("logs/send_map.txt", string(text))
	if err != nil {
		glog.Error(err)
		return
	}
}

func InitTimer() {
	//初始化glist
	L = glist.NewFrom(nil, true)
	//初始化，从文件中获取中断时间的任务，中断期间会以json格式保存任务
	Start()
	//
	gtimer.AddSingleton(5*time.Second, func() {
		//每隔五秒遍历list
		if L.Len() > 0 {
			isPop := 0
			L.Iterator(func(e *glist.Element) bool {
				value := e.Value.(SendMap)
				if value.TimeStamp.Val() < gconv.Int(time.Now().Unix()) {
					fmt.Println(value.ToUserID)
					//发送系统消息
					isPop = 1
					return false
				}
				return true
			})
			if isPop == 1 {
				L.PopFront()
				isPop = 0
			}
		}
		//else {
		//	fmt.Println("list is null")
		//}
		time.Sleep(200 * time.Millisecond)
	})
}
